package com.yiwei.ydd.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;


import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;

import com.yiwei.ydd.R;
import com.yiwei.ydd.constant.FaceBitmap;
import com.yiwei.ydd.event.IdcardFaceEvent;
import com.yiwei.ydd.util.CameraManager;
import com.yiwei.ydd.util.FileUtils;

/**
 * 刷脸界面
 */
public class FaceActivity extends Activity
        implements Callback, OnClickListener {
    private static final String DEFAULT_NAME = "default.jpg";
    private static final String DEFAULT_PATH = "/sdcard/";
    private static final String DEFAULT_TYPE = "default";
    private LinearLayout mBtnView;
    private ImageView back;
    private Bitmap bitmap2;
    private CameraManager cameraManager;
    private boolean safeToTakePicture = false;
    private ImageView take;
    private String type;
    private File file;
    private String fileName;
    private String filePath;
    private boolean hasSurface;
    private boolean isTake;
    private Intent mIntent;
    private TextView rotate;
    private ImageView photo;


    Camera.PictureCallback myjpegCallback = new Camera.PictureCallback() {
        @Override
        public void onPictureTaken(final byte[] data, Camera camera) {
            // 根据拍照所得的数据创建位图
            photo.setVisibility(View.VISIBLE);
            isTake = true;
            back.setImageDrawable(ContextCompat.getDrawable(FaceActivity.this.getApplicationContext(), R.mipmap.error));
            take.setImageDrawable(ContextCompat.getDrawable(FaceActivity.this.getApplicationContext(), R.mipmap.tick));

            bitmap2 = convertBmp(data);
//            Glide.with(FaceActivity.this).load(data).asBitmap().thumbnail(0.3f).
//                    transform(new RotateTransformation(FaceActivity.this, 180f)).
//                    into(new ImageViewTarget<Bitmap>(photo) {
//                        @Override
//                        protected void setResource(Bitmap resource) {
////                            photo.setImageBitmap(resource);
//                            bitmap2 = resource;
//                        }
//                    });
//            Glide.with(FaceActivity.this).load(data).asBitmap().toBytes().thumbnail(0.3f).transform(new RotateTransformation(FaceActivity.this, 180f)).into(new SimpleTarget<byte[]>() {
//                @Override
//                public void onResourceReady(byte[] bytes, GlideAnimation<? super byte[]> glideAnimation) {
//                    try {
//                        bitmap2 = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                }
//            });

//            photo.setVisibility(View.VISIBLE);
//            bitmap2 = convertBmp(data);
//            File path = new File(filePath);
//            if (!path.exists()) {
//                path.mkdirs();
//            }
//            file = new File(path, type + new Date().getTime() + fileName);
//            Log.i("dsadadsadsd", "执行");
            rotate.setVisibility(View.INVISIBLE);

            clearCamera();

        }
    };


    private void initCamera() {
        this.cameraManager = new CameraManager(this, 0);
        SurfaceHolder localSurfaceHolder = ((SurfaceView) findViewById(R.id.surfaceview)).getHolder();
        if (this.hasSurface) {
            initCamera(localSurfaceHolder);
            return;
        }
        localSurfaceHolder.addCallback(this);
    }

    private void initCamera(SurfaceHolder paramSurfaceHolder) {
        if (paramSurfaceHolder == null)
            throw new IllegalStateException("No SurfaceHolder provided");
        if (this.cameraManager.isOpen())
            return;
        try {
            this.cameraManager.openDriver(paramSurfaceHolder);
            this.cameraManager.startPreview();
            this.safeToTakePicture = true;
        } catch (Exception e) {

        }
    }

    private void initIntent() {
        this.mIntent = getIntent();
        this.filePath = this.mIntent.getStringExtra("path");
        this.fileName = this.mIntent.getStringExtra("name");
        this.type = this.mIntent.getStringExtra("type");
        if (this.filePath == null)
            this.filePath = "/sdcard/";
        if (this.fileName == null)
            this.fileName = "default.jpg";
        if (this.type == null)
            this.type = "default";
        Log.e("TAG", this.filePath + "/" + this.fileName + "_" + this.type);
    }

    private void initView() {
        this.photo = (ImageView) findViewById(R.id.photo);
        this.mBtnView = (LinearLayout) findViewById(R.id.ll_btn);
        this.rotate = (TextView) findViewById(R.id.rotate);
        this.take = ((ImageView) findViewById(R.id.take));
        this.back = ((ImageView) findViewById(R.id.back));
        this.take.setOnClickListener(this);
        this.back.setOnClickListener(this);
        this.rotate.setOnClickListener(this);
    }

    public Bitmap convertBmp(byte[] data) {
//        ByteArrayOutputStream dataByte = new ByteArrayOutputStream();
//        paramBitmap.compress(Bitmap.CompressFormat.PNG, 100, dataByte);
//        BitmapFactory.Options opts = new BitmapFactory.Options();
//        opts.inPurgeable = true;// 允许可清除
//        opts.inInputShareable = true;// 以上options的两个属性必须联合使用才会有效果
//        //width，hight设为原来的四分一（inSampleSize等于4）（该参数请使用2的整数倍）,这也减小了位图占用的内存大小；例如，一张//分辨率为2048*1536px的图像使用inSampleSize值为4的设置来解码，
//        // 产生的Bitmap大小约为//512*384px。相较于完整图片占用12M的内存，这种方式只需0.75M内存(假设Bitmap配置为//ARGB_8888)。
//        opts.inSampleSize = 1;//这个是同比例缩放，1就表示同比例缩小一分之一倍。图片文件太大如果不进行设置就会导致OOM错误
//        opts.inPreferredConfig = Bitmap.Config.ARGB_4444;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        options.inPreferredConfig = Bitmap.Config.ARGB_4444;
        BitmapFactory.decodeByteArray(data, 0, data.length, options);
        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, 500, 750);
        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        //            设置图片的缩放大小


        Bitmap paramBitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);
        Matrix localMatrix = new Matrix();
        localMatrix.setRotate(270.0F, paramBitmap.getWidth(), paramBitmap.getHeight());
        localMatrix.postScale(-1.0F, 1.0F);
        Bitmap bitmap = Bitmap.createBitmap(paramBitmap, 0, 0, paramBitmap.getWidth(), paramBitmap.getHeight(), localMatrix, true);
        if (!paramBitmap.isRecycled()) {
            paramBitmap.recycle();
        }
//        Bitmap paramBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
//        int i = paramBitmap.getWidth();
//        int j = paramBitmap.getHeight();
//        Matrix localMatrix = new Matrix();
//        localMatrix.setRotate(270.0F, i, j);
//        localMatrix.postScale(-1.0F, 1.0F);
//        Bitmap bitmap = Bitmap.createBitmap(paramBitmap, 0, 0, i, j, localMatrix, true);
//        paramBitmap.recycle();
        return bitmap;

//        return Bitmap.createBitmap(paramBitmap, 0, 0, paramBitmap.getWidth(), paramBitmap.getHeight(), localMatrix, true);
    }

    public int calculateInSampleSize(
            BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            final int heightRatio = Math.round((float) height
                    / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        return inSampleSize;
    }

    public void onClick(View paramView) {
        switch (paramView.getId()) {
            case R.id.take:
                if (this.isTake) {
                    FileOutputStream outStream = null;
//                    try {
                    // 打开指定文件对应的输出流
                    try {
                        String path = FileUtils.getDiskCacheDir("xinbaobao");
                        file = new File(path, type + new Date().getTime() + fileName);
                        outStream = new FileOutputStream(file);
                        // 把位图输出到指定文件中
                        bitmap2.compress(Bitmap.CompressFormat.JPEG,
                                60, outStream);
                        outStream.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }


//                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
//                    bitmap2.compress(Bitmap.CompressFormat.PNG, 70, baos);
//                    byte[] bitmapByte = baos.toByteArray();
//                        baos.close();
                    FaceBitmap.bitmap = bitmap2;
                    EventBus.getDefault().post(new IdcardFaceEvent());
//                    mIntent = getIntent();
//                        Bundle localBundle = new Bundle();
//                        localBundle.putString("path", this.file.getAbsolutePath());
//                        localBundle.putString("type", this.type);
//                    mIntent.putExtra("bitmap", bitmapByte);
//                    mIntent.putExtra("bitmap", bitmap2);
//                        mIntent.putExtras(localBundle);
//                    setResult(-1, mIntent);
                    finish();
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }


                } else {
                    if (this.safeToTakePicture) {
                        this.cameraManager.takePicture(null, null, this.myjpegCallback);
                        this.safeToTakePicture = false;
                        isTake = false;
                    }
                }
                break;
            case R.id.back:
                if (this.isTake) {
                    photo.setVisibility(View.GONE);
                    rotate.setVisibility(View.VISIBLE);
                    this.isTake = false;
                    this.back.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.mipmap.reback));
                    this.take.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.mipmap.camera));
                    FaceActivity.this.initCamera();
                } else finish();
                break;
            case R.id.rotate:
                cameraManager.setOrientation(180);
                break;
        }
    }

    @Override
    protected void onCreate(Bundle paramBundle) {
        super.onCreate(paramBundle);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(1024, 1024);
        setContentView(R.layout.face_activity);
        initIntent();
        initView();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        clearCamera();
        if (bitmap2 != null && !bitmap2.isRecycled()) {
            bitmap2.recycle();
            bitmap2 = null;
        }
        System.gc();

    }

    private void clearCamera() {
        this.cameraManager.stopPreview();
        this.cameraManager.closeDriver();
        if (!this.hasSurface)
            ((SurfaceView) findViewById(R.id.surfaceview)).getHolder().removeCallback(this);
    }

    public void surfaceChanged(SurfaceHolder paramSurfaceHolder, int paramInt1, int paramInt2, int paramInt3) {
    }

    public void surfaceCreated(SurfaceHolder paramSurfaceHolder) {
        if (!this.hasSurface) {
            this.hasSurface = true;
            initCamera(paramSurfaceHolder);
        }
    }

    public void surfaceDestroyed(SurfaceHolder paramSurfaceHolder) {
        this.hasSurface = false;
    }

    @Override
    protected void onResume() {
        super.onResume();

        initCamera();
    }

    @Override
    protected void onPause() {
        super.onPause();

        clearCamera();
    }
}
